class Meal < ActiveRecord::Base
  
  validates_presence_of :name, :product_ids
  
  belongs_to :user
  
  has_many :meal_line_items
  has_many :meal_comments, :dependent => :destroy
  
  has_many :meal_product_memberships
  has_many :products, :through => :meal_product_memberships
  
  
  def product_ids
    @product_ids || products.map(&:id)
  end
  
  def product_ids=(ids)
    @product_ids = ids.map(&:to_i)
    meal_product_memberships.each do |membership|
      membership.destroy unless ids.include? membership.product_id
    end
   
    ids.each do |id|
      membership = MealProductMembership.create(:product_id => id) unless meal_product_memberships.any? { |d| d.product_id == id }
      self.meal_product_memberships << membership
    end
  end
  
  def price
    total = products.inject(0) do |sum, p|
      sum += p.price
    end
    
    total
  end
end
